package com.example.application.cities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.application.R;
import com.example.application.task.WeatherTask3;

import java.util.HashMap;
import java.util.List;

public class Search extends AppCompatActivity {
    Handler handler;
    String TAG="Search";
    List<HashMap<String, String>> list;
    EditText ed;
    TextView temp,wind,city;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 5) {
                    list = (List<HashMap<String, String>>) msg.obj;
                }
                super.handleMessage(msg);
            }
        };
        WeatherTask3 mytask=new WeatherTask3();
        mytask.setHandler(handler);
        Thread t = new Thread(mytask);
        t.start();
    }
    public void myclick(View w){
        ed = findViewById(R.id.searchtext);
        temp=findViewById(R.id.tw_temp);
        wind=findViewById(R.id.tw_wind);
        city=findViewById(R.id.tw_city);
        if(ed.getText().toString().length()==0){
            Toast.makeText(Search.this, "请输入城市名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if(list==null){
            Toast.makeText(Search.this, "网络正忙，请稍候", Toast.LENGTH_SHORT).show();
        }
        else{
            int i=0;
            for(i=0;i<list.size();i++){
                if(list.get(i).get("city").equals(ed.getText().toString())){
                    temp.setText(list.get(i).get("temp"));
                    wind.setText(list.get(i).get("wind"));
                    city.setText(list.get(i).get("city"));
                    Log.i(TAG, "myclick: "+list.get(i).get("wind"));
                    break;
                }
            }
            if(i==list.size()){
                Toast.makeText(Search.this, "城市输入错误", Toast.LENGTH_SHORT).show();
            }
        }
    }
}